/**
 * 
 */
/**
 * @author Administrator
 *
 */
package app.dao;

import java.util.Calendar;
import java.util.UUID;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;

import app.job.MyJob;
import app.util.Log;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


@Repository
public class CommonDao extends BaseDao{
	@Autowired @Qualifier("Scheduler")
    private Scheduler scheduler;
	
	/**
	 * 添加任务
	 */
	public boolean addJob(String bean) {
		boolean result=false;
		JSONObject myjob=JSONObject.fromObject(bean);
		String id=myjob.getString("id");//id与qrtz_job_details表中的DESCRIPTION字段为，一对一的关系
		long time=myjob.getLong("time");//执行时间
		int type=myjob.getInt("type");//任务类型，1执行一次，2执行无数次
		int control=myjob.getInt("control");//0关闭设备，1打开设备
		String deviceId=myjob.getString("deviceId");//设备ID，多对一
		int week=myjob.getInt("week");
		
		result=addJobQuartz(id,time,type,week);
		
		String sql="insert into myjob values('"+id+"',"+time+","+type+","+control+",'"+deviceId+"',"+week+")";
		result=execute(sql);
		
		return result;
	}
	
	/**
	 * @param id 任务表id quartz任务名
	 */
	public boolean delJob(String id) {
		boolean result=false;
		
		result=delJobQuartz(id);
		
		if(result) {
			String sql="delete from myjob where id='"+id+"'";
			result=execute(sql);
		}
		
		return result;
	}
	public boolean delDevice(String id) {
		boolean result=false;
		
		JSONArray myjobs=listBase("select * from myjob where deviceId='"+id+"'");
		if(myjobs.size()>0) {
			for (int i = 0; i < myjobs.size(); i++) {
				JSONObject myjob=myjobs.getJSONObject(i);
				result=delJob(myjob.getString("id"));
			}
		}else {//没有任务
			result=true;//让删除设备可以继续执行
		}
		
		if(result) {
			String sql="delete from device where id='"+id+"'";
			result=execute(sql);
		}
		return result;
	}
	
	/**
	 * quartz添加任务
	 * @param myJobId myjob表id
	 * @param time 任务执行时间
	 * @param type 任务类型，1执行一次，2执行无数次
	 * @return
	 */
	public boolean addJobQuartz(String myJobId,long time,int type,int week) {
		boolean result=false;
		
		String myJobName=myJobId;
		String myJobGroup="myJobGroup";
		String myJobDescription=myJobId;
		//String myJobExpression="0/1 * * * * ?";//默认每秒一次
		//http://cron.qqe2.com/
		String myJobExpression="";//
		Calendar calendar=Calendar.getInstance();
		calendar.setTimeInMillis(time);
		//0 3 14 6 5 ? 2019-2019 2019年5月6日 14点3分0秒 
		if(type==1) {//执行一次
			myJobExpression=calendar.get(Calendar.MILLISECOND)+" "+calendar.get(Calendar.MINUTE)+" "+calendar.get(Calendar.HOUR_OF_DAY)+" "+calendar.get(Calendar.DATE)+" "+(calendar.get(Calendar.MONTH)+1)+" ? "+calendar.get(Calendar.YEAR)+"-"+calendar.get(Calendar.YEAR);
			Log.outLog("myJobExpression:"+myJobExpression);
		}
		//0 3 14 1-31 1-12 ? * 每年1-12月1-31日 14点3分0秒
		if(type==2) {//执行无数次
			if(week==0) {
				myJobExpression=calendar.get(Calendar.MILLISECOND)+" "+calendar.get(Calendar.MINUTE)+" "+calendar.get(Calendar.HOUR_OF_DAY)+" 1-31 1-12 ?  *";
				Log.outLog("myJobExpression:"+myJobExpression);
			}
			if(week!=0) {
				myJobExpression=calendar.get(Calendar.MILLISECOND)+" "+calendar.get(Calendar.MINUTE)+" "+calendar.get(Calendar.HOUR_OF_DAY)+" ? * "+week+" *";
				Log.outLog("myJobExpression:"+myJobExpression);
			}
		}
		try {
	        //构建job信息
	        JobDetail job = JobBuilder.newJob(MyJob.class).withIdentity(myJobName,myJobGroup).withDescription(myJobDescription).build();
	        // 触发时间点
	        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(myJobExpression);
	        Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger"+myJobName, myJobGroup).startNow().withSchedule(cronScheduleBuilder).build();	
	        //交由Scheduler安排触发
	        scheduler.scheduleJob(job, trigger);
			result=true;
		} catch (Exception e) {
			e.printStackTrace();
			result=false;
		}
		
		return result;
	}
	
	/**
	 * 每隔多少小时执行一次
	 * @param hour
	 * @return
	 */
	public boolean addJobHour(int hour) {
		deleteJobHour();
		boolean result=false;
		String myJobName="myJobName";
		String myJobGroup="myJobGroup";
		String myJobDescription="myJobDescription";
		//String myJobExpression="0/1 * * * * ?";//默认每秒一次
		//http://cron.qqe2.com/
		String myJobExpression="0/"+hour+" * * * * ?";//
		//0 3 14 6 5 ? 2019-2019 2019年5月6日 14点3分0秒 
		//0 3 14 1-31 1-12 ? * 每年1-12月1-31日 14点3分0秒
		try {
	        //构建job信息
	        JobDetail job = JobBuilder.newJob(MyJob.class).withIdentity(myJobName,myJobGroup).withDescription(myJobDescription).build();
	        // 触发时间点
	        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(myJobExpression);
	        Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger"+myJobName, myJobGroup).startNow().withSchedule(cronScheduleBuilder).build();	
	        //交由Scheduler安排触发
	        scheduler.scheduleJob(job, trigger);
			result=true;
		} catch (Exception e) {
			e.printStackTrace();
			result=false;
		}
		return result;
	}
	
	/**
	 * 删除小时工作
	 * @return
	 */
	public boolean deleteJobHour() {
		boolean result=false;
		String myJobName="myJobName";
		String myJobGroup="myJobGroup";
		try {  
            TriggerKey triggerKey = TriggerKey.triggerKey(myJobName, myJobGroup);  
            // 停止触发器  
            scheduler.pauseTrigger(triggerKey);  
            // 移除触发器  
            scheduler.unscheduleJob(triggerKey);  
            // 删除任务  
            scheduler.deleteJob(JobKey.jobKey(myJobName, myJobGroup));  
            result=true;
        } catch (Exception e) {  
        	e.printStackTrace();
        	result=false;
        }  
		return result;
	}
	
	
	
	/**
	 * quartz 删除任务
	 * @param myJobId myjob表id
	 * @param time 任务执行时间
	 * @param type 任务类型，1执行一次，2执行无数次
	 * @return
	 */
	public boolean delJobQuartz(String idMyjob) {
		boolean result=false;
		
		String myJobName=idMyjob;
		String myJobGroup="myJobGroup";
		
		try {  
			  
            TriggerKey triggerKey = TriggerKey.triggerKey(idMyjob, myJobGroup);  
            // 停止触发器  
            scheduler.pauseTrigger(triggerKey);  
            // 移除触发器  
            scheduler.unscheduleJob(triggerKey);  
            // 删除任务  
            scheduler.deleteJob(JobKey.jobKey(myJobName, myJobGroup));  
            result=true;
        } catch (Exception e) {  
        	e.printStackTrace();
        	result=false;
        }  
		
		return result;
	}
	
}